import React from 'react';
import * as THREE from 'three';
import Scene from '../Scene';

export default class TestModel {
    constructor(){
        this.scene = new Scene();
        this.canvasScene = this.scene.scene;
        this.init();
    }
    init(){
        console.log(THREE);
        let vertexShader = `
            varying vec3 vColor;
            uniform vec3 upColor;
            uniform vec3 upColor2;
            uniform vec3 bottomColor;
            uniform float time;
            uniform float speed;
            void main(){
                vec3 dissColor = upColor2 - upColor;
                vec3 newPosition = position;
                vColor = bottomColor;
                if ( position.y > 0.0 ) {
                    vColor = upColor + dissColor * abs(cos(time));                
                    newPosition.y -= abs(cos(time)) * speed;
                }
                gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(newPosition, 1.0);
            }
        `;
        let fragmentShader = `
            varying vec3 vColor;
            void main(){
                gl_FragColor = vec4(vColor, 1.0); 
            }
        `;
        let boxMtl = new THREE.ShaderMaterial({
            vertexShader,
            fragmentShader,
            uniforms:{
                upColor:{ value:new THREE.Color('#ff0000') },
                upColor2:{ value:new THREE.Color('#00ff1a') },
                bottomColor:{ value:new THREE.Color('#000000' )},
                time:{ value:0 },
                speed:{ value:1 }
            }
        })
        // 创建多个长方体模型
        let shaders = [], meshs = [];
        for ( let i=0; i<100; i++){
            
            let height = Math.random() * 10;
            let itemShader = boxMtl.clone();
            shaders.push(itemShader);
            let boxMesh = new THREE.Mesh(
                new THREE.BoxGeometry(Math.random() + 0.2 , height, Math.random()),
                itemShader
            );
            
            // 每个模型都更新自身的材质信息
            itemShader.uniforms.upColor.value.g = Math.random();
            itemShader.uniforms.upColor2.value.g = Math.random();
            itemShader.uniforms.speed.value = (0.5 - Math.random()) * 10;
            boxMesh.position.x = ( 0.5 - Math.random()) * 10;
            boxMesh.position.y = height / 2;
            boxMesh.position.z = ( 0.5 - Math.random()) * 10;
            this.canvasScene.add(boxMesh);   
        }
        animate();
        function animate(){
            shaders.forEach(shader=>{
                shader.uniforms.time.value += 0.01;
            })
            requestAnimationFrame(animate);
        }

    }
}